﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject;
using Ninject.Modules;
using Tools.DataAccess.Common;
using Tools.Model;

namespace Tools.DataAccess.Repository
{
    public class UnitOfWork : IDisposable, IUnitOfWork
    {
        private IDbContext _context;
        private Dictionary<Type, object> _repositories;
        //private bool _disposed;

        public UnitOfWork(string connectionString)
        {
            //_context = new TContext(connectionString);
            _context = NinjectConfig.kernel.
                Get<IDbContext>(new Ninject.Parameters.ConstructorArgument("connectionString", connectionString));
            _repositories = new Dictionary<Type, object>();
        }

        public IRepository<TEntity> GetRepository<TEntity>() where TEntity : EntityBase
        {
            if (!_repositories.Keys.Contains(typeof(TEntity)))
                _repositories.Add(typeof(TEntity), new Repository<TEntity>(_context));
            return _repositories[typeof(TEntity)] as IRepository<TEntity>;
        }

        public int Save()
        {
            return _context.Save();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
